package img

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"path"
	"time"
)

type PostIMG struct {
	beego.Controller
}

func (c *PostIMG) PostIMG() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/img/PostIMG"
	var err error
	img := &Admin.IMG{}
	res := &resMes.PostIMG{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	sessionUnkown := c.Ctx.Request.Header["Session"]
	//fmt.Println([]byte(c.GetString("activity")))

	if len(sessionUnkown) == 0 {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}
	session := sessionUnkown[0]
	if session == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}

	ses, err := session2.FindSession(session)
	//fmt.Println(ses.Admin)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	} else if ses == nil {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "404", "session过期")
		return
	} else if ses.Admin == nil {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "400", "未登录")
		return
	}
	if ses.Admin.Privilege != 1 && ses.Admin.ActivityManagement != 1 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "400", "无权限")
		return
	}

	f, h, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	defer func() {
		err = f.Close()
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}()
	//fmt.Println(f,h)
	//1.限定格式
	//拿到文件的后缀名
	fileExt := path.Ext(h.Filename)
	if fileExt != ".jpg" && fileExt != ".png" {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "403", "图片格式错误")
		return
	}
	//2.限制大小
	if h.Size > 5000000 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "405", "图片过大")
		return
	}
	//3.对文件重命名避免重复+时间戳 2006-01-02 15:04:05 go语言诞生时间 可正常格式化时间
	//随机数也可
	fileName := time.Now().Format("2006-01-02 15-04-05")
	//beego.Info(fileName)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	//     “.”必须
	err = c.SaveToFile("img", "./static/img/"+fileName+h.Filename)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	img.Name = h.Filename
	img.Url = "/static/img/" + fileName + h.Filename
	res.Mes = "success"
	res.IMG = img
	res.Code = "200"
	c.Data["json"] = res
}
